package com.medical.literature.search.controller;

import com.medical.literature.common.vo.PageResult;
import com.medical.literature.common.vo.Result;
import com.medical.literature.search.dto.SearchRequest;
import com.medical.literature.search.dto.SearchResultItem;
import com.medical.literature.search.service.SearchService;
import com.medical.literature.search.service.impl.SearchServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 搜索控制器
 */
@Slf4j
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {
    
    private final SearchService searchService;

    /**
     * 文献搜索
     */
    @PostMapping("/literature")
    public Result<PageResult<SearchResultItem>> searchLiterature(
            @RequestHeader("X-User-Id") Long userId,
            @Valid @RequestBody SearchRequest request) {
        
        // 保存搜索历史
        searchService.saveSearchHistory(userId, request.getKeyword());
        
        // 执行搜索
        PageResult<SearchResultItem> result = searchService.searchLiterature(request, userId);
        return Result.success(result);
    }

    /**
     * 获取搜索历史
     */
    @GetMapping("/history")
    public Result<List<String>> getSearchHistory(@RequestHeader("X-User-Id") Long userId) {
        List<String> history = searchService.getRecentSearchHistory(userId, 10);
        return Result.success(history);
    }

    /**
     * 清除搜索历史
     */
    @DeleteMapping("/history")
    public Result<Void> clearSearchHistory(@RequestHeader("X-User-Id") Long userId) {
        searchService.clearSearchHistory(userId);
        return Result.success();
    }

    /**
     * 热门搜索关键词
     */
    @GetMapping("/hot-keywords")
    public Result<List<String>> getHotKeywords() {
        List<String> hotKeywords = searchService.getHotKeywords(10);
        return Result.success(hotKeywords);
    }
}